package org.example.filter;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.HygResponse;
import org.example.base.MyRequestWrapper;
import org.example.utils.BusinessCode;
import org.example.utils.IpUtil;
import org.example.utils.WriterUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liyishan
 * @date 2023/7/20 13:47
 * @apiNote
 */
@Slf4j
@WebFilter("/*")
public class CacheFilter implements Filter {

    public void init(FilterConfig filterConfig) {
        log.info("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)throws IOException, ServletException {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();

        long start = System.currentTimeMillis();
        log.info("鉴权过滤器开始执行");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        String realIp = IpUtil.getRealIp(request);
        log.info("openApi请求ip:{}, uri:{}.", realIp, requestURI);
        MyRequestWrapper myRequestWrapper = new MyRequestWrapper(request);
        String body = myRequestWrapper.getBody();
        //健康检测
        if ("/".equals(requestURI)) {
            WriterUtil.writerJson(response, new HygResponse<>(BusinessCode.SUCCESS));
            return;
        }
        if (StringUtils.isEmpty(body)) {
            //WriterUtil.writerJson(response, new HygResponse<>(BusinessCode.ERROR_PARAMS));
            log.error("请求参数为空 ip:{}, URI:{}", realIp, requestURI);
            //return;
        }
        //todo  对body进行脱敏处理并做业务参数非空校验,业务参数逻辑校验,获取白名单后做ip白名单校验，获取AES秘钥对body解密，获取RSA公钥对参数去除sign参数然后排序 最后对sign验签
        //todo  对参数里的时间戳校验不超过10分钟
        //把处理后的参数重新赋值给request
        myRequestWrapper.setBody(body);
        //保存请求日志
        chain.doFilter(myRequestWrapper,response);
        log.info("Api request uri:{},use time :{}ms.\n", requestURI, System.currentTimeMillis() - start);

    }



    @Override
    public void destroy() {
        log.info("过滤器已销毁");
    }
}

